package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
)

func main() {
	fmt.Println("pid: ", os.Getpid())
	serveMux := &http.ServeMux{}
	serveMux.HandleFunc("/sleep", sleep)
	server := &http.Server{Addr: ":8080", Handler: serveMux}
	go func() {
		if err := server.ListenAndServe(); err != nil {
			fmt.Println(err)
		}
	}()

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	<-ch
	err := server.Shutdown(context.Background()) //可以定义shutting down的超时时间，超时时间一到，强制关闭
	if err != nil {
		fmt.Println(err)
	}
}

func sleep(writer http.ResponseWriter, request *http.Request) {
	_ = request.ParseForm()
	ts, _ := strconv.ParseInt(request.FormValue("time"), 10, 64)
	fmt.Printf("sleep %d seconds\n", ts)
	time.Sleep(time.Second * time.Duration(ts))
	writer.WriteHeader(http.StatusOK)
}
